Skip to content

Replace suboptimal O(n) time/space inorder vector approach with O(k + h) time, O(h) space recursive solution that short-circuits once the kth smallest is found#113

Open
ultrakapy wants to merge 1 commit intoByteByteGoHq:mainfrom
ultrakapy:main
Open

Replace suboptimal O(n) time/space inorder vector approach with O(k + h) time, O(h) space recursive solution that short-circuits once the kth smallest is found#113
ultrakapy wants to merge 1 commit intoByteByteGoHq:mainfrom
ultrakapy:main

Conversation

@ultrakapy
Copy link

The previous implementation collected all node values into a vector via a full inorder traversal before indexing into it, resulting in O(n) time and O(n) space regardless of where the kth smallest element sits in the tree.

The new implementation passes k by reference as a countdown and short-circuits as soon as it reaches zero. When the kth node is found, the return prevents any further right subtree traversal in that frame. For ancestors that were waiting on a left call, the if (k == 0) return guard intercepts them before they descend right, ensuring no unnecessary nodes are visited after the answer is found.

This brings time complexity down to O(k + h) and space complexity down to O(h), where h is the height of the tree. In the worst case (skewed tree) h = n, but for balanced trees this is a significant improvement over the previous approach.

…(h) space recursive solution that short-circuits once the kth smallest is found
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant